<?
class Feedback_model extends CI_Model
{
	function __construct()
	{
		parent::__construct();
	}

	function addLetter($post)
	{
		if (empty($post['page']))
			return false;
		$page = (int)$post['page'];
		unset($post['page']);

		$pageRow = $this->db->where(array(
			'id' => $page,
			'pType' => 3,
			'dDeleted' => 0
		))->get('page')->row();

		if (empty($pageRow))
			return false;

		if (!($feedback = $this->db->where('tPage', $page)->get('feedback')->row()))
			return false;

		$feedback = json_decode($feedback->pJSON);

		$upd = array();
		$emailText = '';
		foreach ($feedback as $fb)
		{
			if ($this->user->id && $fb[1]=="pName")
				$upd['pName'] = $this->user->data->pName;
			elseif ($this->user->id && $fb[1]=="pEmail")
				$upd['pEmail'] = $this->user->data->pEmail;
			
			if (isset($post[$fb[1]]))
			{
				if (empty($upd[$fb[1]]))
					$upd[$fb[1]] = $post[$fb[1]];

				unset($post[$fb[1]]);
			}
			else
			{
				if (empty($upd[$fb[1]]))
					return false;
			}
			$emailText .= '<b>'.$fb[0].'</b>:<br>'.$upd[$fb[1]].'<br>';
		}

		if (!empty($post))
			return false;

		if ($this->settings->data->pFeedbackEmail)
		{

			if (empty($this->mail))
				$this->load->model('email_model', 'mail');
			$this->mail->sendEmail($this->settings->data->pFeedbackEmail,
				$pageRow->pName.' - '.$this->settings->data->title,
				$emailText);
		}

		return $this->db->insert('letters', array(
				'tPage' => $page,
				'pVals' => json_encode($upd)
			));
	}

	function getFeedback($id = 0)
	{
		if (!$id)
			return array();
		
		if ($res = $this->db->where('tPage', $id)->get('feedback')->row())
			return json_decode($res->pJSON);
		else
			return array();
	}

	function getLetters()
	{
		return $this->db->get('letters')->result();
	}
}